fs = require 'fs'
path = require 'path'
util = require 'util' 
express = require 'express'
log = require('./utils/log').getLogger()
lessMiddleware = require 'less-middleware'

configureRouters = (app) ->
	fs.readdirSync(path.join __dirname,'routes').forEach (file) ->
		return if file?[0] is '.'
		name = path.basename file, path.extname file
		m = require "./routes/#{file}"
		for key,value of m
			app[key.split(' ')[0]] key.split(' ')[1], value

app = express()
app.configure ->
	app.disable 'view cache'
	app.set 'views', path.join __dirname,'views'
	app.set 'view engine', 'jade'
	app.use express.compress()
	app.use express.errorHandler()
	app.use express.cookieParser()
	app.use express.bodyParser {maxFieldsSize:5696893,uploadDir: '/tmp'}
	configureRouters app
	app.get '/health', (req, res, next) -> res.send 200, "alive"
	app.use lessMiddleware({
		src: __dirname + '/public',
		compress: false
	})
	app.use '/', express.static "#{__dirname}/public"
	app.use express.query()
	app.use '/wechat', require './robots'
	app.use (err ,req, res, next)->
		if err
			log.error err?.stack ? util.inspect err
			res.send 500,err.msg

process.on 'uncaughtException', (err)->
	log.error err?.stack ? util.inspect err
	
port = parseInt process.argv[2]

unless port > 1000
	console.error "usage: node #{__filename} <port>"
	process.exit 1
	return

app.listen port
log.warn "listen #{port}"
